//
//  caredb.m
//  tcpoctest
//
//  Created by apple on 13-3-13.
//  Copyright (c) 2013年 gump. All rights reserved.
//

#import "caredb.h"
#import "CareDataSource.h"

@implementation caredb

-(void)creatTable
{
    if(db != nil)
    {
        pthread_mutex_lock(&mutexdatabase);
        
        [db open];
        [db executeUpdate:@"create table if not exists careperson(\
id int IDENTITY(1,1),mail text,firendmail text)"];
        [db close];
        
        pthread_mutex_unlock(&mutexdatabase);
    }
}

-(void)initData
{
    if (db == nil) {
        return;
    }
    
    NSString *str = [NSString stringWithFormat:@"select firendmail from careperson where mail = '%@'",
                     [DataControl shareControl].personDS.uinfo.mail];
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    
    FMResultSet *s = [db executeQuery:str];
    
    [[DataControl shareControl].careds RemoveAllShowArr];
    
    while ([s next])
    {
        [[DataControl shareControl].careds AddShowArrObject:[s stringForColumn:@"firendmail"]];
    }
    
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

-(void)insertCare:(NSString *)mail
{
    if (db == nil) {
        return;
    }
    
    NSString *strsql = [NSString stringWithFormat:
                        @"insert into careperson (mail,firendmail) values('%@','%@')"
                        ,[DataControl shareControl].personDS.uinfo.mail
                        ,mail];
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    
    [db executeUpdate:strsql];
    
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

-(void)deleteAll
{
    if (db == nil) {
        return;
    }
    
    NSString *strsql = [NSString stringWithFormat:
                        @"DELETE FROM careperson WHERE mail = '%@'"
                        ,[DataControl shareControl].personDS.uinfo.mail];
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    
    [db executeUpdate:strsql];
    
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

-(void)deleteItem:(NSString *)mail
{
    if (db == nil) {
        return;
    }
    
    NSString *strsql = [NSString stringWithFormat:
                        @"DELETE FROM careperson WHERE mail = '%@' and firendmail = '%@'"
                        ,[DataControl shareControl].personDS.uinfo.mail
                        ,mail];
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    
    [db executeUpdate:strsql];
    
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

@end
